﻿using System.Net.Http;
using System.Threading.Tasks;
using Volo.Abp.Json;

namespace Wuther.Infrastructure.WeChat
{
    public class WechatAppService : IWechatAppService
    {
        private readonly IJsonSerializer _jsonSerializer;

        public WechatAppService(IJsonSerializer jsonSerializer)
        {
            _jsonSerializer = jsonSerializer;
        }

        public IJsonSerializer JsonSerializer => _jsonSerializer;

        public async Task<LoginResult> GetWeChatSessionAsync(string code)
        {
            //微信开发平台验证
            string _appid = "wx4af871e75b85ef59";
            string _secret = "b9c8e72687468ea384c13d1b7c7c6c05";

            string url = string.Format(
                "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code",
                _appid,
                _secret,
                code);
            HttpClient client = new HttpClient();
            HttpResponseMessage response = await client.GetAsync(url);
            if (response.IsSuccessStatusCode)
            {
                string resContent = await response.Content.ReadAsStringAsync();
                var result = _jsonSerializer.Deserialize<LoginResult>(resContent);
                return result;
            }
            return new LoginResult()
            {
                errcode = (int)response.StatusCode,
                errmsg = response.RequestMessage.ToString()
            };
        }
    }
}
